<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
   
  <meta name="keywords" content="Java Python" />
   
  <meta name="description" content="From Zero to Hero" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    Netty-06-核心组件 |  朱酱酱的学习博客
  </title>
  <meta name="generator" content="hexo-theme-yilia-plus">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/css/style.css">

  
<script src="/js/pace.min.js"></script>


  

  

<link rel="alternate" href="/atom.xml" title="朱酱酱的学习博客" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    <main class="content">
      <section class="outer">
  <article id="post-Netty/Netty-06-核心组件" class="article article-type-post" itemscope
  itemprop="blogPost" data-scroll-reveal>

  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Netty-06-核心组件
</h1>
  

    </header>
    

    
    <div class="article-meta">
      <a href="/2020/10/28/Netty/Netty-06-%E6%A0%B8%E5%BF%83%E7%BB%84%E4%BB%B6/" class="article-date">
  <time datetime="2020-10-28T10:05:24.000Z" itemprop="datePublished">2020-10-28</time>
</a>
      
      
      
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.4k字</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">9分钟</span>
        </span>
    </span>
</div>

      
    </div>
    

    
    
    <div class="tocbot"></div>





    

    <div class="article-entry" itemprop="articleBody">
      


      

      
      <h1 id="Netty-06-核心组件"><a href="#Netty-06-核心组件" class="headerlink" title="Netty-06-核心组件"></a>Netty-06-核心组件</h1><h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><ul>
<li><strong>本文注重讲解Netty的核心组成</strong></li>
</ul>
<p><img src="http://zhuuu-bucket.oss-cn-beijing.aliyuncs.com/img/20201024/085701217.png" alt="mark"></p>
<h2 id="1-Bootstrap、ServerBootstrap"><a href="#1-Bootstrap、ServerBootstrap" class="headerlink" title="1. Bootstrap、ServerBootstrap"></a>1. Bootstrap、ServerBootstrap</h2><ul>
<li><code>Bootstrap</code> 意思是引导，一个 <code>Netty</code> 应用通常由一个 <code>Bootstrap</code> 开始，主要作用是配置整个 <code>Netty</code> 程序，串联各个组件，<code>Netty</code> 中 <code>Bootstrap</code> 类是客户端程序的启动引导类，<code>ServerBootstrap</code> 是服务端启动引导类</li>
</ul>
<p><strong>常见方法：</strong></p>
<table>
<thead>
<tr>
<th>方法名称</th>
<th>方法介绍</th>
</tr>
</thead>
<tbody><tr>
<td><code>public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup)</code></td>
<td>该方法用于服务器端，用来设置两个EventLoop</td>
</tr>
<tr>
<td><code>public B group(EventLoopGroup group)</code></td>
<td>该方法用于客户端，用来设置一个EventLoop</td>
</tr>
<tr>
<td><code>public B channel(Class&lt;? extends C&gt; channelClass)</code></td>
<td>该方法用来设置一个服务器端的通道实现</td>
</tr>
<tr>
<td><code>public &lt;T&gt; B option(ChannelOption&lt;T&gt; option, T value)</code></td>
<td>用来给 ServerChannel 添加配置</td>
</tr>
<tr>
<td><code>public &lt;T&gt; ServerBootstrap childOption(ChannelOption&lt;T&gt; childOption, T value)</code></td>
<td>用来给接收到的通道添加配置</td>
</tr>
<tr>
<td><code>public ServerBootstrap childHandler(ChannelHandler childHandler)</code></td>
<td>该方法用来设置业务处理类（自定义的 handler）</td>
</tr>
<tr>
<td><code>public ChannelFuture bind(int inetPort)</code></td>
<td>该方法用于服务器端，用来设置占用的端口号</td>
</tr>
<tr>
<td><code>public ChannelFuture connect(String inetHost, int inetPort)</code></td>
<td>该方法用于客户端，用来连接服务器</td>
</tr>
</tbody></table>
<a id="more"></a>



<h2 id="2-Future、ChannelFuture"><a href="#2-Future、ChannelFuture" class="headerlink" title="2. Future、ChannelFuture"></a>2. Future、ChannelFuture</h2><ul>
<li><code>Netty</code> 中所有的 <code>IO</code> 操作都是异步的，不能立刻得知消息是否被正确处理。但是可以过一会等它执行完成或者直接注册一个监听，具体的实现就是通过 <code>Future</code> 和 <code>ChannelFuture</code>，他们可以注册一个监听，当操作执行成功或失败时监听会自动触发注册的监听事件</li>
</ul>
<p><strong>常见的方法有</strong></p>
<table>
<thead>
<tr>
<th>方法名</th>
<th>方法介绍</th>
</tr>
</thead>
<tbody><tr>
<td><code>Channel channel()</code></td>
<td>返回当前正在进行 IO 操作的通道</td>
</tr>
<tr>
<td><code>ChannelFuture sync()</code></td>
<td>等待异步操作执行完毕，相当于将阻塞在当前。</td>
</tr>
</tbody></table>
<h2 id="3-Channel"><a href="#3-Channel" class="headerlink" title="3. Channel"></a>3. Channel</h2><ul>
<li><p><code>Netty</code> 网络通信的组件，能够用于执行网络 <code>I/O</code> 操作。</p>
</li>
<li><p>通过<code>Channel</code> 可获得当前网络连接的通道的状态</p>
</li>
<li><p>通过<code>Channel</code> 可获得 网络连接的配置参数 （例如接收缓冲区大小）</p>
</li>
<li><p><code>Channel</code> 提供异步的网络 <code>I/O</code> 操作(如建立连接，读写，绑定端口)，<strong>异步调用意味着任何 <code>I/O</code> 调用都将立即返回，并且不保证在调用结束时所请求的 <code>I/O</code> 操作已完成</strong></p>
</li>
<li><p><strong>调用立即返回一个 <code>ChannelFuture</code> 实例，通过注册监听器到 <code>ChannelFuture</code> 上，可以 <code>I/O</code> 操作成功、失败或取消时回调通知调用方</strong></p>
</li>
<li><p><strong>不同协议、不同的阻塞类型的连接都有不同的 <code>Channel</code> 类型与之对应</strong></p>
</li>
</ul>
<p><strong>常用的 <code>Channel</code> 类型</strong></p>
<table>
<thead>
<tr>
<th>名称</th>
<th>介绍</th>
</tr>
</thead>
<tbody><tr>
<td><code>NioSocketChannel</code></td>
<td>异步的客户端 TCP Socket 连接。</td>
</tr>
<tr>
<td><code>NioServerSocketChannel</code></td>
<td>异步的服务器端 TCP Socket 连接</td>
</tr>
<tr>
<td><code>NioDatagramChannel</code></td>
<td>异步的 UDP 连接。</td>
</tr>
<tr>
<td><code>NioSctpChannel</code></td>
<td>异步的客户端 Sctp 连接。</td>
</tr>
<tr>
<td><code>NioSctpServerChannel</code></td>
<td>异步的 Sctp 服务器端连接，这些通道涵盖了 UDP 和 TCP 网络 IO 以及文件 IO。</td>
</tr>
</tbody></table>
<h2 id="4-Seletor"><a href="#4-Seletor" class="headerlink" title="4. Seletor"></a>4. Seletor</h2><ul>
<li><p><strong><code>Netty</code> 基于 <code>Selector</code> 对象实现 <code>I/O</code> 多路复用，通过 <code>Selector</code> 一个线程可以监听多个连接的 <code>Channel</code> 事件。</strong></p>
</li>
<li><p>当向一个 <code>Selector</code> 中注册 <code>Channel</code> 后，<code>Selector</code> 内部的机制就可以自动不断地查询(<code>Select</code>) 这些注册的 <code>Channel</code> 是否有已就绪的 <code>I/O</code> 事件（例如可读，可写，网络连接完成等），这样程序就可以<strong>很简单地使用一个线程高效地管理多个 <code>Channel</code></strong></p>
</li>
<li><p>同时，<code>Netty</code>中对<code>selector</code>中的<code>selectedKey</code>集合进行了替换，它替换成了一个它自己实现的一个<code>set</code>集合，这样效率更高。</p>
</li>
</ul>
<h2 id="5-ChannelHandler"><a href="#5-ChannelHandler" class="headerlink" title="5. ChannelHandler"></a>5. ChannelHandler</h2><p><img src="http://zhuuu-bucket.oss-cn-beijing.aliyuncs.com/img/20201022/123220946.png" alt="mark"></p>
<ul>
<li><strong><code>ChannelHandler</code> 是一个接口，处理 <code>I/O</code> 事件或拦截 <code>I/O</code> 操作，并将其转发到其 <code>ChannelPipeline</code>(业务处理链)中的下一个处理程序。</strong></li>
<li><strong><code>ChannelHandler</code> 本身并没有提供很多方法，因为这个接口有许多的方法需要实现，方便使用期间，可以继承它的子类</strong></li>
<li>我们经常需要<strong>自定义一个<code>Handler</code> 类去继承<code>ChannelInboundHandlerAdapter</code> ，然后通过相应方法实现业务逻辑，来看看有哪些方法需要重写</strong></li>
</ul>
<p><img src="http://zhuuu-bucket.oss-cn-beijing.aliyuncs.com/img/20201028/224217480.png" alt="mark"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ChannelInboundHandlerAdapter</span> <span class="keyword">extends</span> <span class="title">ChannelHandlerAdapter</span> <span class="keyword">implements</span> <span class="title">ChannelInboundHandler</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//通道注册事件</span></span><br><span class="line">    <span class="meta">@Skip</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelRegistered</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        ctx.fireChannelRegistered();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//通道取消注册事件</span></span><br><span class="line">    <span class="meta">@Skip</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelUnregistered</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        ctx.fireChannelUnregistered();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//通道就绪事件</span></span><br><span class="line">    <span class="meta">@Skip</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        ctx.fireChannelActive();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Calls &#123;<span class="doctag">@link</span> ChannelHandlerContext#fireChannelInactive()&#125; to forward</span></span><br><span class="line"><span class="comment">     * to the next &#123;<span class="doctag">@link</span> ChannelInboundHandler&#125; in the &#123;<span class="doctag">@link</span> ChannelPipeline&#125;.</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * Sub-classes may override this method to change behavior.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Skip</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelInactive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        ctx.fireChannelInactive();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//通道读取数据事件</span></span><br><span class="line">    <span class="meta">@Skip</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        ctx.fireChannelRead(msg);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//通道数据读取完毕事件</span></span><br><span class="line">    <span class="meta">@Skip</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelReadComplete</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        ctx.fireChannelReadComplete();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Calls &#123;<span class="doctag">@link</span> ChannelHandlerContext#fireUserEventTriggered(Object)&#125; to forward</span></span><br><span class="line"><span class="comment">     * to the next &#123;<span class="doctag">@link</span> ChannelInboundHandler&#125; in the &#123;<span class="doctag">@link</span> ChannelPipeline&#125;.</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * Sub-classes may override this method to change behavior.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Skip</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">userEventTriggered</span><span class="params">(ChannelHandlerContext ctx, Object evt)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        ctx.fireUserEventTriggered(evt);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Calls &#123;<span class="doctag">@link</span> ChannelHandlerContext#fireChannelWritabilityChanged()&#125; to forward</span></span><br><span class="line"><span class="comment">     * to the next &#123;<span class="doctag">@link</span> ChannelInboundHandler&#125; in the &#123;<span class="doctag">@link</span> ChannelPipeline&#125;.</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * Sub-classes may override this method to change behavior.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Skip</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelWritabilityChanged</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        ctx.fireChannelWritabilityChanged();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//通道发生异常事件</span></span><br><span class="line">    <span class="meta">@Skip</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="meta">@SuppressWarnings</span>(<span class="string">"deprecation"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">exceptionCaught</span><span class="params">(ChannelHandlerContext ctx, Throwable cause)</span></span></span><br><span class="line"><span class="function">            <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        ctx.fireExceptionCaught(cause);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<ul>
<li><strong>再来回顾一下类图</strong></li>
</ul>
<p><img src="http://zhuuu-bucket.oss-cn-beijing.aliyuncs.com/img/20201028/224217480.png" alt="mark"></p>
<ul>
<li><code>ChannelInboundHandler</code> 用于处理入站 I/O 事件。</li>
<li><code>ChannelOutboundHandler</code> 用于处理出站 I/O 操作。</li>
</ul>
<p><strong>适配器</strong></p>
<ul>
<li><code>ChannelInboundHandlerAdapter</code> 用于处理入站 I/O 事件。</li>
<li><code>ChannelOutboundHandlerAdapter</code> 用于处理出站 I/O 操作。</li>
<li><code>ChannelDuplexHandler</code> 用于处理入站和出站事件。</li>
</ul>
<h2 id="7-Pipeline-和-ChannelPipeline"><a href="#7-Pipeline-和-ChannelPipeline" class="headerlink" title="7. Pipeline 和 ChannelPipeline"></a>7. Pipeline 和 ChannelPipeline</h2><ul>
<li><code>ChannelPipeline</code> 是一个 <code>Handler</code> 的集合，它负责处理和拦截 <code>inbound</code> 或者 <code>outbound</code> 的事件和操作，相当于一个贯穿 <code>Netty</code> 的链。(也可以这样理解：<code>ChannelPipeline</code> 是 保存 <code>ChannelHandler</code> 的 <code>List</code>，用于处理或拦截 <code>Channel</code> 的入站事件和出站操作)</li>
<li><code>ChannelPipeline</code> 实现了一种高级形式的拦截过滤器模式，使用户可以完全控制事件的处理方式，以及 <code>Channel</code> 中各个的 <code>ChannelHandler</code> 如何相互交互</li>
<li>在 <code>Netty</code> 中每个 <code>Channel</code> 都有且仅有一个 <code>ChannelPipeline</code> 与之对应，它们的组成关系如下</li>
</ul>
<p><img src="http://zhuuu-bucket.oss-cn-beijing.aliyuncs.com/img/20201022/123220946.png" alt="mark"></p>
<p><strong>组成关系</strong></p>
<ul>
<li>一个 <code>Channel</code> 包含了一个 <code>ChannelPipeline</code>，而 <code>ChannelPipeline</code> 中又维护了一个由 <code>ChannelHandlerContext</code> 组成的<strong>双向链表</strong>，并且每个 <code>ChannelHandlerContext</code> 中又关联着一个 <code>ChannelHandler</code></li>
<li><strong>入站事件和出站事件在一个双向链表中</strong>，入站事件会从链表 <code>head</code> 往后传递到最后一个入站的 <code>handler</code>，出站事件会从链表 <code>tail</code> 往前传递到最前一个出站的 <code>handler</code>，两种类型的 <code>handler</code> 互不干扰</li>
</ul>
<p><strong>常用方法：</strong></p>
<table>
<thead>
<tr>
<th>方法名</th>
<th>介绍</th>
</tr>
</thead>
<tbody><tr>
<td><code>ChannelPipeline addFirst(ChannelHandler... handlers)</code></td>
<td>把一个业务处理类（handler）添加到链中的第一个位置</td>
</tr>
<tr>
<td>ChannelPipeline addLast(ChannelHandler… handlers)</td>
<td>把一个业务处理类（handler）添加到链中的最后一个位置</td>
</tr>
</tbody></table>
<h2 id="8-ChannelOption"><a href="#8-ChannelOption" class="headerlink" title="8. ChannelOption"></a>8. ChannelOption</h2><ul>
<li><code>Netty</code> 在创建 <code>Channel</code> 实例后,一般都需要设置 <code>ChannelOption</code> 参数。</li>
</ul>
<p><strong>ChannelOption 参数如下</strong></p>
<p><code>ChannelOption.SO_BACKLOG</code></p>
<ul>
<li><strong>对应 TCP/IP 协议 listen 函数中的 backlog 参数，用来初始化服务器可连接队列大小。</strong></li>
<li>服务端处理客户端连接请求是顺序处理的，所以同一时间只能处理一个客户端连接。多个客户端来的时候，<strong>服务端将不能处理的客户端连接请求放在队列中等待处理，backlog 参数指定了队列的大小。</strong></li>
</ul>
<p><code>ChannelOption.SO_KEEPALIVE</code></p>
<ul>
<li><strong>一直保持TCP连接活动的状态</strong></li>
</ul>
<h2 id="9-EventLoopGroup-和-NioEventLoopGroup"><a href="#9-EventLoopGroup-和-NioEventLoopGroup" class="headerlink" title="9. EventLoopGroup 和 NioEventLoopGroup"></a>9. EventLoopGroup 和 NioEventLoopGroup</h2><ul>
<li><code>EventLoopGroup</code> 是一组 <code>EventLoop</code> 的抽象，Netty为了更好的利用多核CPU资源，一般会有多个<code>EventLoop</code> 同时工作，每个<code>EventLoop</code>维护着一个Selector 实例</li>
</ul>
<p><img src="http://zhuuu-bucket.oss-cn-beijing.aliyuncs.com/img/20201029/092123789.png" alt="mark"></p>
<ul>
<li><code>EventLoopGroup</code> 提供 next 接口，可以从组里面按照一定规则获取其中一个 <code>EventLoop</code>来处理任务。<ul>
<li>在 Netty 服务器端编程中，我们一般都需要提供两个 <code>EventLoopGroup</code>，例如：<code>BossEventLoopGroup</code> 和<code>WorkerEventLoopGroup</code>。</li>
</ul>
</li>
<li>通常一个服务端口即一个<code>ServerSocketChannel</code> 对应一个 <code>Selector</code> 和 一个<code>EventLoop</code> 线程。<ul>
<li>BossEventLoop 负责接收客户端的连接并将 SocketChannel 交给 WorkerEventLoopGroup 来进行 IO 处理</li>
</ul>
</li>
<li>BossEventLoopGroup 通常是一个单线程的 EventLoop，EventLoop 维护者一个注册了ServerSocketChannel 的Selector 实例BossEventLoop 不断轮询 Selector 将连接事件分离出来<ul>
<li>通常是 OP_ACCEPT 事件，然后将接收到的 SocketChannel 交给 WorkerEventLoopGroup</li>
<li>WorkerEventLoopGroup 会由 next 选择其中一个EventLoop 来讲这个SocketChannel 注册到其维护的Selector 并对和后续的IO事件进行处理</li>
</ul>
</li>
</ul>
<p><strong>常用方法：</strong></p>
<table>
<thead>
<tr>
<th>方法名</th>
<th>介绍</th>
</tr>
</thead>
<tbody><tr>
<td><code>public NioEventLoopGroup()</code></td>
<td>构造方法</td>
</tr>
<tr>
<td><code>public Future&lt;?&gt; shutdownGracefully()</code></td>
<td>断开连接，关闭线程</td>
</tr>
</tbody></table>
<h2 id="10-ByteBuf"><a href="#10-ByteBuf" class="headerlink" title="10. ByteBuf"></a>10. ByteBuf</h2><ul>
<li><strong>Netty 提供一个专门用来操作缓冲区(即Netty的数据容器)的工具类</strong></li>
</ul>
<p><strong>常用方法</strong></p>
<table>
<thead>
<tr>
<th>方法名</th>
<th>介绍</th>
</tr>
</thead>
<tbody><tr>
<td><code>public static ByteBuf copiedBuffer(CharSequence string, Charset charset)</code></td>
<td>通过给定的数据和字符编码返回一个 ByteBuf 对象（类似于 NIO 中的 ByteBuffer 但有区别）</td>
</tr>
</tbody></table>
<ul>
<li><strong>使用举例</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建一个ByteBuf</span></span><br><span class="line"><span class="comment">//1、创建对象，该对象包含一个数组，是一个byte[10]</span></span><br><span class="line"><span class="comment">//2、在netty的buffer中，写入数据后再读取数据不需要使用 flip 进行反转</span></span><br><span class="line"><span class="comment">// 底层维护了 readerIndex 和 writeIndex</span></span><br><span class="line"><span class="comment">//往buffer中写的范围为 [writeIndex, capacity)</span></span><br><span class="line"><span class="comment">//往buffer中可读的范围为 [readerIndex, writeIndex)。使用 buf.readByte() 会往后移动 readerIndex 指针，使用 buf.getByte(i) 通过索引获取就不会移动该指针</span></span><br><span class="line">ByteBuf byteBuf = Unpooled.buffer(<span class="number">10</span>);</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">    byteBuf.writeByte(i);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//获取该buf的大小</span></span><br><span class="line"><span class="keyword">int</span> capacity = byteBuf.capacity();</span><br><span class="line"><span class="comment">//输出</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; byteBuf.capacity(); i++) &#123;</span><br><span class="line">    System.out.println(byteBuf.getByte(i));</span><br><span class="line">    System.out.println(byteBuf.readByte());</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">byte</span>[] content = byteBuf.array();</span><br><span class="line"><span class="comment">//将content转成字符串</span></span><br><span class="line">String c = <span class="keyword">new</span> String(content, StandardCharsets.UTF_8);</span><br><span class="line"><span class="comment">//数组偏移量</span></span><br><span class="line"><span class="keyword">int</span> offset = byteBuf.arrayOffset();</span><br><span class="line"><span class="comment">//获取读取偏移量</span></span><br><span class="line"><span class="keyword">int</span> readerIndex = byteBuf.readerIndex();</span><br><span class="line"><span class="comment">//获取写偏移量</span></span><br><span class="line"><span class="keyword">int</span> writerIndex = byteBuf.writerIndex();</span><br><span class="line"><span class="comment">//获取容量</span></span><br><span class="line"><span class="keyword">int</span> capacity = byteBuf.capacity();</span><br><span class="line"><span class="comment">//获取可读取的字节数</span></span><br><span class="line"><span class="keyword">int</span> readableBytes = byteBuf.readableBytes();</span><br><span class="line"><span class="comment">//通过索引获取某个位置的字节</span></span><br><span class="line"><span class="keyword">byte</span> aByte = byteBuf.getByte(<span class="number">0</span>);</span><br><span class="line"><span class="comment">//获取Buf中某个范围的字符序列</span></span><br><span class="line">CharSequence charSequence = byteBuf.getCharSequence(<span class="number">0</span>, <span class="number">4</span>, StandardCharsets.UTF_8);</span><br></pre></td></tr></table></figure>


      
      <!-- reward -->
      
      <div id="reward-btn">
        打赏
      </div>
      
    </div>
      <!-- copyright -->
      
        <div class="declare">
          <ul class="post-copyright">
            <li>
              <i class="ri-copyright-line"></i>
              <strong>版权声明： </strong s>
              本博客所有文章除特别声明外，均采用 <a href="https://www.apache.org/licenses/LICENSE-2.0.html" rel="external nofollow"
                target="_blank">Apache License 2.0</a> 许可协议。转载请注明出处！
            </li>
          </ul>
        </div>
        
    <footer class="article-footer">
      
          
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://zhuuu.work/2020/10/28/Netty/Netty-06-%E6%A0%B8%E5%BF%83%E7%BB%84%E4%BB%B6/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/NIO/" rel="tag">NIO</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Netty/" rel="tag">Netty</a></li></ul>


    </footer>

  </div>

  
  
  <nav class="article-nav">
    
      <a href="/2020/10/29/Leetcode/Leetcode-129-%E6%B1%82%E6%A0%B9%E5%88%B0%E5%8F%B6%E5%AD%90%E8%8A%82%E7%82%B9%E6%95%B0%E5%AD%97%E4%B9%8B%E5%92%8C/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Leetcode-129-求根到叶子节点数字之和
          
        </div>
      </a>
    
    
      <a href="/2020/10/28/Netty/Netty-07-%E7%BE%A4%E8%81%8A%E7%B3%BB%E7%BB%9F%E5%AE%9E%E7%8E%B0/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Netty-07-群聊系统实现</div>
      </a>
    
  </nav>


  

  
  
<!-- valine评论 -->
<div id="vcomments-box">
    <div id="vcomments">
    </div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/valine@1.3.10/dist/Valine.min.js'></script>
<script>
    new Valine({
        el: '#vcomments',
        notify: false,
        verify: '',
        app_id: '',
        app_key: '',
        path: window.location.pathname,
        avatar: 'mp',
        placeholder: '给我的文章加点评论吧~',
        recordIP: true
    });
    const infoEle = document.querySelector('#vcomments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
        infoEle.childNodes.forEach(function (item) {
            item.parentNode.removeChild(item);
        });
    }
</script>
<style>
    #vcomments-box {
        padding: 5px 30px;
    }

    @media screen and (max-width: 800px) {
        #vcomments-box {
            padding: 5px 0px;
        }
    }

    #vcomments-box #vcomments {
        background-color: #fff;
    }

    .v .vlist .vcard .vh {
        padding-right: 20px;
    }

    .v .vlist .vcard {
        padding-left: 10px;
    }
</style>

  

  
  
<div class="gitalk" id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1.5.0/dist/gitalk.css">


<script src="https://cdn.jsdelivr.net/npm/gitalk@1.5.0/dist/gitalk.min.js"></script>


<script src="https://cdn.jsdelivr.net/npm/blueimp-md5@2.10.0/js/md5.min.js"></script>

<script type="text/javascript">
  var gitalk = new Gitalk({
    clientID: 'db188ed8c86dc4b0dbf3',
    clientSecret: 'a58f92160e5a9efd726b7d533000a0737f3e3f3e',
    repo: 'Blog-comments',
    owner: 'Zhuuuuuuuu',
    admin: ['Zhuuuuuuuu'],
    // id: location.pathname,      // Ensure uniqueness and length less than 50
    id: md5(location.pathname),
    distractionFreeMode: false,  // Facebook-like distraction free mode
    pagerDirection: 'last'
  })

  gitalk.render('gitalk-container')
</script>

  

</article>
</section>
      <footer class="footer">
  <div class="outer">
    <ul class="list-inline">
      <li>
        &copy;
        2019-2021
        Zhuuu
      </li>
      <li>
        
      </li>
    </ul>
    <ul class="list-inline">
      <li>
        
        
        <span>
  <i>PV:<span id="busuanzi_value_page_pv"></span></i>
  <i>UV:<span id="busuanzi_value_site_uv"></span></i>
</span>
        
      </li>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
    <div class="to_top">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>
      </div>
    </main>
      <aside class="sidebar">
        <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="朱酱酱的学习博客"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/JVM/">JVM</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/JDK%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/">JDK源码</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/">多线程</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Mysql/">Mysql</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Redis/">Redis</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E8%AE%BE%E8%AE%A1%E8%80%85%E6%A8%A1%E5%BC%8F/">设计模式</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/MyBatis/">MyBatis</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/SpringMVC/">SpringMVC</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Spring/">Spring</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/SpringBoot/">SpringBoot</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Linux</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Leetcode/">Leetcode</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E5%89%8D%E7%AB%AF/">前端</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/">网络编程</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/photoshop/">photoshop</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="http://smartzhuuu.lofter.com/" target="_blank" rel="noopener">摄影</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2020/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
      </aside>
      <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
      
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/jquery.justifiedGallery.min.js"></script>


<script src="/js/lazyload.min.js"></script>


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<script src="/js/share.js"></script>



<script src="/fancybox/jquery.fancybox.min.js"></script>




<script>
  try {
    var typed = new Typed("#subtitle", {
    strings: ['昨夜西风凋碧树。独上高楼，望尽天涯路','衣带渐宽终不悔，为伊消得人憔悴。','众里寻他千百度。蓦然回首，那人却在，灯火阑珊处。'],
    startDelay: 0,
    typeSpeed: 200,
    loop: true,
    backSpeed: 100,
    showCursor: true
    });
  } catch (err) {
  }
  
</script>




<script src="/js/tocbot.min.js"></script>

<script>
  // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer:'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
    onClick: (e) => {
      $('.toc-link').removeClass('is-active-link');
      $(`a[href=${e.target.hash}]`).addClass('is-active-link');
      $(e.target.hash).scrollIntoView();
      return false;
    }
  });
</script>


<script>
  var ayerConfig = {
    mathjax: true
  }
</script>


<script src="/js/ayer.js"></script>


<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>



<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>


<script type="text/javascript" src="https://js.users.51.la/20544303.js"></script>
  </div>
</body>

</html>